<?php

/**
 * Manage data of "User" table
 * 
 * @author Tham
 */
class User {

    const TABLENAME = "travel_users";

    public function mail_utf8($to, $from_user, $from_email, $subject = '(No subject)', $message = '') {
        $from_user = "=?UTF-8?B?" . base64_encode($from_user) . "?=";
        $subject = "=?UTF-8?B?" . base64_encode($subject) . "?=";

        $headers = "From: $from_user <$from_email>\r\n" .
                "MIME-Version: 1.0" . "\r\n" .
                "Content-type: text/html; charset=UTF-8" . "\r\n";

        return mail($to, $subject, $message, $headers);
    }

    /*
      author:tham
      check username on database
      @param $username
      @return true or false
     */

    public static function checkUserNameByUserName($username) {

        global $post, $wpdb;
        $sql = "SELECT count(ID) as countname  FROM " . self::TABLENAME . "  WHERE `user_login`='" . $username . "'";
        $myrows = $wpdb->get_results($sql);

        $n = $myrows[0]->countname;
        if ($n == 0) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * check if email is existed
     *
     * @param $email
     * @return boolean
     * @author:tham
     */
    public static function checkUserNameByEmail($email) {


        global $post, $wpdb;
        $sql = "SELECT count(ID) as countname  FROM " . self::TABLENAME . " WHERE `user_email`='" . $email . "'";
        $myrows = $wpdb->get_results($sql);
        $n = $myrows[0]->countname;
        if ($n == 0) {
            return false;
        } else {
            return true;
        }
    }

    public static function add_user($data) {

        global $post, $wpdb;
        $user = '';
        $sql1 = 'SELECT * FROM ' . self::TABLENAME . ' order by ID DESC';
        $myrows = $wpdb->get_results($sql1);
        $id_user_new = (int) $myrows[0]->ID + 1;

        $first_name = $data['first_name'];
        $location = $data['location'];

        $type_user = $data['type_user'];
        $last_name = $data['last_name'];
        $password = $data['password'];

        $email = $data['email'];

        $state_province = $data['state'];
        $city = $data['city'];
        $postcode = $data['postcode'];
        $country = $data['country'];
        $ponit_add = $data['ponit_add'];

        update_user_meta($id_user_new, 'first_name', $first_name);  //*update user data  first_name */
        update_user_meta($id_user_new, 'last_name', $last_name);   //*update user data  last_name */
        update_user_meta($id_user_new, 'nickname', $last_name);  //*update user data  first_name */
        update_user_meta($id_user_new, 'type_user', $type_user);  //*update user data  first_name */
        // check user on database



        $sql_insert = "INSERT INTO `" . self::TABLENAME . "` (`ID`, `user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `display_name`,state_province,city,postcode,country)"
                . " VALUES(" . $id_user_new . ", '" . $user . "', '" . md5($password) . "', '" . $last_name . "', '" . $email . "', '', '" . date('Y-m-d') . "','" . $first_name . "','" . $state_province . "','" . $city . "','" . $postcode . "','" . $country . "')";

        $wpdb->query($sql_insert);

        return $id_user_new;
    }

    public function edit_user($data) {
        global $post, $wpdb;
        $id_user = $data['id_user'];

        $first_name = $data['first_name'];

        $type_user = $data['type_user'];
        $last_name = $data['last_name'];
        $cc = $data['password'];
        $password = md5($cc);
        $email = $data['email'];
        $user = $data['username'];
        $state_province = $data['state'];
        $city = $data['city'];
        $postcode = $data['postcode'];
        $country = $data['country'];

        update_user_meta($id_user, 'first_name', $first_name);  //*update user data  first_name */
        update_user_meta($id_user, 'last_name', $last_name);   //*update user data  last_name */
        update_user_meta($id_user, 'nickname', $last_name);  //*update user data  first_name */
        update_user_meta($id_user, 'location', $location);  //*update user data  first_name */
        $sql = " UPDATE `" . self::TABLENAME . "` 
						 SET    `user_login` = '" . $user . "',";
        if ($data['password'] <> "") {
            $sql = $sql . " `user_pass` = '" . $password . "', ";
        }

        $sql = $sql . "   `user_nicename`       = '" . $last_name . "',
				                `user_email`          = '" . $email . "',
								`display_name`        = '" . $last_name . "',
								`state_province`      = '" . $state_province . "',
								`city`                = '" . $city . "',
								`postcode` 			  = '" . $postcode . "',
								`country` 		      = '" . $country . "',
                                                                 phone_number        ='" . $data['phone_number'] . "',
								`website`             = '" . $data['website'] . "'
						  WHERE `ID` = " . $id_user;
        $wpdb->query($sql);
        $myrows = self::get_user_by_userID($id_user);
        $_SESSION['userlogin']['username'] = $myrows[0]->user_login;
        $_SESSION['userlogin']['user_status'] = $myrows[0]->user_status;
        $_SESSION['userlogin']['display_name'] = $myrows[0]->display_name;
        $_SESSION['userlogin']['state_province'] = $myrows[0]->state_province;
        $_SESSION['userlogin']['city'] = $myrows[0]->city;
        $_SESSION['userlogin']['postcode'] = $myrows[0]->postcode;
        $_SESSION['userlogin']['address'] = $myrows[0]->address;
        $_SESSION['userlogin']['country'] = $myrows[0]->country;
        $_SESSION['userlogin']['latitude'] = $myrows[0]->latitude;
        $_SESSION['userlogin']['longtitude'] = $myrows[0]->longtitude;
    }

    /*
     * check user and pass of users
     * @param array $data['username'] and $data['pass']
     * @return case  = 1 // User OK
     * @return case  = -1 // User OK Not active 
     * @return case  = 0  // User not pass not exsit
     */

    public function get_user_buy_username_password($data) {

        global $wpdb;
        $username = $data['username'];
        $pass = md5($data['password']);
        $sql1 = "SELECT * FROM `" . self::TABLENAME . "` where user_email = '" . $username . "' and user_pass ='" . $pass . "'";
        // echo $sql1;
        $myrows = $wpdb->get_results($sql1);
        if (count($myrows) > 0) {

            $ID_NEW = $myrows[0]->ID;
            $active = $myrows[0]->active;
            if ($active == 1) {
                $_SESSION['userlogin']['ID'] = $ID_NEW;
                $first_name = get_user_meta($ID_NEW, 'first_name');
                $first_name = $first_name[0];
                $_SESSION['userlogin']['first_name'] = $first_name;

                $last_name = get_user_meta($ID_NEW, 'last_name');
                $last_name = $last_name[0];
                $_SESSION['userlogin']['last_name'] = $last_name;
                $_SESSION['userlogin']['email'] = $myrows[0]->user_email;

                $location = get_user_meta($ID_NEW, 'location');
                $location = $location[0];
                $_SESSION['userlogin']['location'] = $location;
//                $type_user = get_user_meta($ID_NEW, 'type_user');		                
                $type_user = $myrows[0]->type_user;
                $_SESSION['userlogin']['type_user'] = $type_user;

                //@author:Tuan	      
                $_SESSION['userlogin']['username'] = $myrows[0]->user_login;
                $_SESSION['userlogin']['user_status'] = $myrows[0]->user_status;
                $_SESSION['userlogin']['display_name'] = $myrows[0]->display_name;
                $_SESSION['userlogin']['state_province'] = $myrows[0]->state_province;
                $_SESSION['userlogin']['city'] = $myrows[0]->city;
                $_SESSION['userlogin']['postcode'] = $myrows[0]->postcode;
                $_SESSION['userlogin']['address'] = $myrows[0]->address;
                $_SESSION['userlogin']['country'] = $myrows[0]->country;
                $_SESSION['userlogin']['latitude'] = $myrows[0]->latitude;
                $_SESSION['userlogin']['longtitude'] = $myrows[0]->longtitude;

                return 1;
            } else {

                return -1;
            }
            //end Tuan
            //  print_r($_SESSION['userlogin']);
        } else {
            return 0;
        }
    }

    public function get_user_by_userID($id_user) {
        global $post, $wpdb;
        $username = $data['username'];
        $pass = md5($data['password']);
        $sql1 = "SELECT * FROM `" . self::TABLENAME . "` where ID = " . $id_user;
        $myrows = $wpdb->get_results($sql1);
        return $myrows;
    }

    public static function ActiveAccount($id_user, $forgot_key) {

        global $post, $wpdb;

        $sql = " UPDATE `" . self::TABLENAME . "` 
						 SET    `forgot_key` = '" . $forgot_key . "',
						         active       = 1
						        
						 WHERE `ID` = " . $id_user;

        $wpdb->query($sql);
    }

    public static function CheckUserByEmailUser($email, $user) {
        global $post, $wpdb;
        $sql1 = "SELECT * FROM `" . self::TABLENAME . "` where   user_login = '" . $user . "' and  user_email='" . $email . "'";
        $myrows = $wpdb->get_results($sql1);
        //print_r($myrows);
        $thongbao = "";
        if (count($myrows) > 0) {

            $thongbao = "";

            $chuoirand = Helper::rand_string(10);
            $md4_chuoi = md5($chuoirand);
            //echo $chuoirand;
            $sql = " UPDATE `gorave_users` 
								 SET    `user_pass` = '" . $md4_chuoi . "'
								 WHERE `ID` = " . $myrows[0]->ID;
            $id_user = $myrows[0]->ID;
            $wpdb->query($sql);
            MailHelper::SendMailFogetPass($chuoirand, $myrows);
            $thongbao = "Password is send your email .Please check your email ";
        } else {
            $thongbao = "User or Email isn't true ";
        }

        return $thongbao;
    }

    // @author :than
    // Get kist user bay email
    public static function CheckUserByEmail($email) {
        global $post, $wpdb;
        $sql1 = "SELECT * FROM `" . self::TABLENAME . "` where  user_email='" . $email . "'";
        $myrows = $wpdb->get_results($sql1);
        //print_r($myrows);
        $thongbao = "";
        if (count($myrows) > 0) {

            $thongbao = "";

            $chuoirand = Helper::rand_string(10);
            $md4_chuoi = md5($chuoirand);
            //echo $chuoirand;
            $sql = " UPDATE `" . self::TABLENAME . "` 
								 SET    `user_pass` = '" . $md4_chuoi . "'
								 WHERE `ID` = " . $myrows[0]->ID;
            $id_user = $myrows[0]->ID;
            $wpdb->query($sql);
            MailHelper::SendMailFogetPass($chuoirand, $myrows);
            $thongbao = "Password is sent to your email .Please check your email ";
        } else {
            $thongbao = "Email isn't true ";
        }

        return $thongbao;
    }

    /*
     */

    public static function EditUserField($namefield, $value, $id_user) {


        global $post, $wpdb;
        $id_user = (float) $id_user;

        //echo $namefield.'|'.$value.'|'.$id_user.'<br/>';
        if ($id_user > 0) {
            $namefield = (string) $namefield;
            $value = (string) $value;
            if ($namefield == 'type_user') {
                $sql = "UPDATE `" . self::TABLENAME . "` 
									 SET    " . $namefield . " = " . $value . "
									 WHERE `ID` = " . $id_user;
            } else {
                $value = (string) $value;
                $sql = "UPDATE `" . self::TABLENAME . "` 
									 SET    " . $namefield . " = '" . $value . "'
									 WHERE `ID` = " . $id_user;
                //echo $sql;
                //exit();
            }
            // echo $sql;

            $wpdb->query($sql);
        }
    }

    //get id_user oder by ID on add_user paged 
    public static function List_Oder_by_ID_User() {
        global $post, $wpdb;
        $sql1 = "SELECT * FROM `" . self::TABLENAME . "` order by ID DESC";
        $myrows = $wpdb->get_results($sql1);
        $ID_NEW = (int) $myrows[0]->ID;

        return $ID_NEW;
    }

    //get All User on admin paged
    public static function ListAllUserAdminPage($role = "") {
        global $post, $wpdb;
        if ($role == "") {
            $sql1 = "SELECT * FROM `" . self::TABLENAME . "` as A  order by ID DESC";
        } else {

            $sql1 = "SELECT * FROM `" . self::TABLENAME . "` as A 
			         WHERE `ID` in (SELECT user_id from  `gorave_usermeta` Where `meta_key`= 'gorave_capabilities' and `meta_value` like '%" . $role . "%' ) 
					  order  by  A.ID DESC";
        }


        $myrows = $wpdb->get_results($sql1);
        return $myrows;
    }

    /*
     * author: Tham
     * @param:$ID
     * @return $list
     * Get list all Post by User ID 
     */

    public static function GetAllPostByIDUser($ID) {
        global $post, $wpdb;
        $sql = "SELECT count(ID) as count FROM `" . self::TABLENAME . "` WHERE `post_author` = " . $ID . " and  `post_type`= 'post'";
        $myrows = $wpdb->get_results($sql);
        return $myrows[0]->count;
    }

    /*
     * author:Tham
     * Get Ds User by ID User
     * @param :$ID
     * return $listpost
     */

    public static function GetUserByIDUser($ID) {
        global $post, $wpdb;
        $sql = "SELECT count(ID) as count FROM `" . self::TABLENAME . "` WHERE  ID = " . $ID;
        $listpost = $wpdb->get_results($sql);
        return $listpost;
    }

    /*
     * author: Tham
     * Deleteuser by id user in admin
     * @param : $ID
     * return none
     */

    public static function DeteleUserByID($id_user) {
        global $post, $wpdb;
        $sql = "DELETE FROM `" . self::TABLENAME . "` WHERE `ID` = " . $id_user;
        $wpdb->query($sql);
    }

}
